const http = require("http");
const fs = require("fs");
const path = require("path");
const serve = http.createServer();
var dirname = "static"
serve.on("request", (req, res) => {
    var filepath = path.join(__dirname, dirname, req.url)
    if (req.url == "/") {
        filepath = path.join(__dirname, dirname, "index.html")
    }
    if (req.url == "/favicon.ico") {
        filepath = path.join(__dirname, dirname, "img", "120px-八奈見杏菜.jpg")
    }
    var data = fs.readFileSync(filepath);
    res.end(data);
});

serve.listen("3000", () => {
    console.log("服务启动成功,请访问http://10.10.49.42:3000/,或http://127.0.0.1:3000/,或http://localhost:3000/");
})

// 服务器
const socketio=require('socket.io');
const io =socketio.listen(serve);
var users = [];
var stop = "";
io.on('connection',(socket)=>{
    console.log("有人连接");
    users.push(socket);
    //接收
    socket.on("info",(data)=>{
        console.log(data);
        users.forEach((item)=>{
            item.emit("result",data)
        })
    });
    //管理员公告
    clearInterval(stop);
    stop = setInterval(()=>{
        console.log("管理员公告发送");
        users.forEach((item)=>{
            item.emit("result",{name:"管理员",value:"维护良好讨论环境,人人有责(此消息每10秒自动发送)"})
        })
    },10000);
})

io.on('disconnect',()=>{
    console.log("有人离开");
})







// const wss = new websocket.Server({ port: "3000" });
// wss.on('connection', (ws) => {
//     console.log('有人来了~~');
//     ws.on('message', (data) => {
//         ws.send(data + '举头望明月');
//     })
//     ws.on('close', () => {
//         console.log('客人走了');
//     })
// })